package cn.tedu.luban.passport.main.service;

import cn.tedu.luban.passport.main.repository.PassportRepository;
import cn.tedu.luban.passport.protocol.bo.UserBO;
import cn.tedu.luban.passport.protocol.common.encoder.JwtEncoder;
import cn.tedu.luban.passport.protocol.common.enums.PassportResultEnum;
import cn.tedu.luban.passport.protocol.jwt.UserPrinciple;
import cn.tedu.luban.passport.protocol.param.UserLoginParam;
import cn.tedu.luban.passport.protocol.param.UserRegistryParam;
import com.tedu.inn.commons.utils.Asserts;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PassportService {
    @Autowired
    private PassportRepository passportRepository;
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    public UserBO login(UserLoginParam param) throws BusinessException {
        UserBO userBO=passportRepository.getUserByUsername(param.getUsername());
        Asserts.isTrue(userBO==null||userBO.getId()==null,new BusinessException(PassportResultEnum.USER_NONE_EXIST));
        Asserts.isTrue(!userBO.getPassword().equals(param.getPassword()),new BusinessException(PassportResultEnum.USER_PASSWORD_ERROR));
        UserPrinciple userPrinciple=new UserPrinciple();
        BeanUtils.copyProperties(userBO,userPrinciple);
        String jwt=generateToken(userPrinciple);
        userBO.setJwt(jwt);
        userBO.setHeaderName("Authorization");
        userBO.setType("Bearer");
        return userBO;
    }

    private String generateToken(UserPrinciple principle) throws BusinessException {
        return jwtEncoder.generateToken(principle);
    }

    public Long addNewUser(UserRegistryParam param) throws BusinessException {
        Long total = passportRepository.countUserByUsername(param.getUsername());
        Asserts.isTrue(total>0,new BusinessException(PassportResultEnum.USER_EXIST));
        return passportRepository.addNewUser(param);
    }
}
